package com.nep.NEPG;

import com.nep.NEPG.model.SystemUser;
import com.nep.NEPG.repository.UserRepository;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.UUID;

public class MainApp extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            // 初始化示例数据
            initSampleData();

            // 加载登录视图（更新路径）
            FXMLLoader loader = new FXMLLoader(
                    getClass().getResource("/com/nep/NEPG/view/LoginView.fxml"));
            Parent root = loader.load();

            Scene scene = new Scene(root);
            primaryStage.setScene(scene);
            primaryStage.setTitle("登录 - 环保公众监督平台");
            primaryStage.setResizable(false); // 建议登录页固定大小
            primaryStage.setOnCloseRequest(event -> {
                Platform.exit();
                System.exit(0);
            });
            primaryStage.show();
        } catch (IOException e) {
            showErrorAndExit("应用程序初始化错误", "无法加载登录界面：" + e.getMessage());
        } catch (Exception e) {
            showErrorAndExit("应用程序错误", "启动时发生错误：" + e.getMessage());
        }
    }

    private void initSampleData() {
        try {
            UserRepository userRepository = new UserRepository();

            // 检查是否已有用户
            if (userRepository.findAll().isEmpty()) {
                // 添加网格员样例账户
                SystemUser gridEmployee = new SystemUser(
                        UUID.randomUUID().toString(),
                        "griduser",
                        "password",
                        "GRID_EMPLOYEE");
                userRepository.save(gridEmployee);

                // 添加管理员账户
                SystemUser admin = new SystemUser(
                        UUID.randomUUID().toString(),
                        "admin",
                        "admin123",
                        "ADMIN");
                userRepository.save(admin);

                System.out.println("已创建示例用户：griduser/password, admin/admin123");
            }
        } catch (Exception e) {
            System.err.println("[警告] 示例数据初始化失败: " + e.getMessage());
        }
    }

    private void showErrorAndExit(String title, String message) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
        Platform.exit();
        System.exit(1);
    }

    public static void main(String[] args) {
        // 环境检查增强版
        checkRuntimeEnvironment();

        // 启动日志
        System.out.println("=== 应用程序启动 ===");
        System.out.println("版本: 1.0.0");
        System.out.println("包路径: com.nep.NEPG");

        launch(args);
    }

    private static void checkRuntimeEnvironment() {
        String javaVersion = System.getProperty("java.version");
        String javafxVersion = System.getProperty("javafx.version");

        // 最低要求：Java 11 + JavaFX 11
        if (Integer.parseInt(javaVersion.split("\\.")[0]) < 11) {
            showEnvErrorAndExit("需要Java 11或更高版本，当前版本: " + javaVersion);
        }

        if (javafxVersion == null) {
            showEnvErrorAndExit("JavaFX运行时未检测到，请确保:\n" +
                    "1. 使用JDK包含JavaFX（如Amazon Corretto 11+）\n" +
                    "2. 或已添加JavaFX SDK依赖");
        }
    }

    private static void showEnvErrorAndExit(String message) {
        System.err.println("环境检查失败: " + message);
        new Alert(AlertType.ERROR, message).showAndWait();
        Platform.exit();
        System.exit(1);
    }
}